package com.app.miwawa.api.system.service.bo;

import java.util.List;

import javax.annotation.Resource;

import org.framework.common.api.entity.CommonEntityAware;
import org.framework.common.api.query.Criterion.Operator;
import org.framework.common.api.service.bo.CommonBoAdapter;
import org.framework.common.api.service.dao.CommonDaoAware;
import org.framework.common.api.support.constant.SystemConstants;
import org.framework.common.api.support.model.PageModel;
import org.framework.common.api.support.model.QueryModel;
import org.framework.common.api.support.model.TreeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.app.miwawa.api.system.entity.Groups;
import com.app.miwawa.api.system.entity.center.Relation;
import com.app.miwawa.api.system.service.dao.RelationDao;

/**
 * 业务接口
 * <p>描述: 角色－业务接口</p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年1月23日 上午9:37:10
 * @version 1.0.2016
 */
@Service("groupsBo")
public class GroupsBo extends CommonBoAdapter<Groups, String> {

	@Resource(name = "defaultDao")
	private CommonDaoAware<CommonEntityAware<String>, String> dao;
	
	@Autowired
	private RelationDao relationDao;
	
	/**
	 * @see org.framework.common.api.service.bo.CommonBoAdapter#tree(org.framework.common.api.support.model.QueryModel)
	 * @author chanlong(陈龙)
	 * @param groupsid 
	 * @date 2016年4月1日 下午2:19:43
	 */
	public TreeModel[] tree(final String usersid, final QueryModel model) throws Exception {
		List<?> result = dao.findByQuery(model).getRows();
		
		return TreeModel.create(result, getRelations(usersid));
	}
	
	/**
	 * 删除绑定角色.
	 * @param groupsid
	 * @author chanlong(陈龙)
	 * @date 2016年4月1日 下午5:32:39
	 */
	public void deleteRelations(final String usersid){
		relationDao.delete(usersid);
	}
	
	/*
	 * 获取用户角色关系
	 */
	private String[] getRelations(final String usersid) throws Exception{
		QueryModel query = new QueryModel();
		query.setEntityClass(Relation.class);
		query.addAndQuery("source", "Users", Operator.EQ);
		query.addAndQuery("sourceid", usersid, Operator.EQ);
		query.addAndQuery("status", SystemConstants.DICT_STATUS_DEFAULT, Operator.EQ);
		query.addAndQuery("invalid", SystemConstants.DICT_DELETE_INVALID, Operator.EQ);
		
		String[] groupsids = null;
		PageModel<?> result = dao.findByQuery(query);
		if(result != null){
			List<Relation> relations = result.getRows(Relation.class);
			
			int size = relations.size();
			groupsids = new String[size];
			
			for (int i = 0; i < size; i++) {
				groupsids[i] = relations.get(i).getTargetid();
			}
		}
		System.out.println(groupsids);
		return groupsids;
	}
}
